<template>
  <div class="overflow-auto h-[100%]" v-loading="loading">
    <VForm
      class="freight-form"
      ref="form"
      :model="model"
      :fieldList="fieldList"
      :options="formOption"
      :rules="rules"
      :disabled="disabled"
      :originOption="{ ...optionsData, ...options }"
    >
      <template #Number="{ input, value }">
        <Number @input="input" :value="value" @change="handleOrder" />
      </template>
      <template #SkuQuantity="{ input, value }">
        <SkuQuantity
          @input="input"
          :value="value"
          @change="handleSkuQuantity"
        />
      </template>
      <template #platform="{ input, value }">
        <PlatformSelect @update:model-value="input" :model-value="value" />
      </template>
      <template #warehouse="{ input, value }">
        <WarehouseSelect @update:model-value="input" :model-value="value" />
      </template>
      <template #destination_country="{ input, value }">
        <WarehouseSelect @update:model-value="input" :model-value="value" />
      </template>
      <template #volume="{ input, value }">
        <Volume @input="input" :value="value" />
      </template>
    </VForm>
    <div>
      <el-button :loading="loading" type="primary" @click="handleSubmit">
        计算
      </el-button>
      <el-button :loading="loading" @click="handleReset">重置</el-button>
      <!-- <el-button text type="primary" @click="handleSelling">售价试算</el-button> -->
    </div>
    <div
      class="text-[12px] text-[#333] leading-[22px] bg-[var(--base-small-bg-color)] rounded-[8px] px-[8px] py-[8px] my-[16px]"
    >
      <p class="text-[14px] font-[600]">说明</p>
      <p v-for="item in tips" :key="item">{{ item }}</p>
    </div>
  </div>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import VForm from "@/components/Form/index.vue";
import WarehouseSelect from "@/components/WarehouseSelect/index.vue";
import PlatformSelect from "@/components/PlatformSelect/index.vue";
import Volume from "@/components/Volume/index.vue";
import Number from "./components/Number/index";
import { objectToArray } from "../hooks/index.js";
import { getLogisticsAttr } from "@/api/public.js";
import SkuQuantity from "./components/SkuQuantity/index";
import { useEnumSelect } from "@/hooks/useEnumSelect.js";
import {
  getSkuDetails,
  getOrderDetail,
  getOrderShipmentInfo,
} from "@/api/crossSys.js";
import { freightCalc } from "../api";
import { getCountry } from "@/api/index.js";
const tips = [
  `1. 根据订单查询：只输入订单号，计算该订单所有SKU运费。`,
  `2. 根据产品查询：输入SKU、数量、目的国家，计算指定SKU运费。`,
  `3. 根据重量尺寸查询：输入包裹重量、目的国家，长宽高计算运费。`,
  `4. 当有订单号时，输入包裹重量、长宽高、目的国家、产品属性 和 平台无效。`,
  `5. 根据订单查询：当输入SKU时，输入包裹重量、长宽高、产品属性无效。`,
  `6. 同时输入订单号、SKU，表示该订单中此SKU的运费。`,
  `7. 产品属性为非必填项，平台默认为Amazon，数量不输入时默认为1。`,
  `8、当选择发货仓及目的仓，根据类型为头程优选的渠道报价（取平均费用）计算。`,
  `9、若开启使用物流商API计算则必须要填写邮编。`,
];

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  options: { type: Object, default: () => ({}) },
});

const emit = defineEmits(["tableData", "selling"]);

const formOption = {
  inline: true,
  labelPosition: "top",
};

const rules = {
  destination_country: [
    { required: true, message: "请选择目的国家", trigger: "blur" },
  ],
  freight_calc_mode: [
    { required: true, message: "运费计算模式", trigger: "blur" },
  ],
};

const form = ref();
const model = ref({
  delivery_mode: [1, 3],
  freight_calc_mode: 1,
});
const loading = ref();
const optionsData = ref({});
const handleSkuQuantity = (val) => {
  let formValues = form.value.getFormValues();
  model.value = Object.assign({}, formValues, {
    volume: val?.volume || [],
    package_weight: val?.package_weight || null,
  });
};
const handleOrder = async (val) => {
  if (!val?.customer_order_no) {
    model.value = {
      ono_type: val?.ono_type,
      delivery_mode: val?.ono_type == 1 ? [1, 3] : [2],
    };
  }
  if (!val?.ono_type || !val?.customer_order_no) return;
  if (val.ono_type == 1) {
    getOrder(val.customer_order_no);
  } else {
    getOrderShipment(val.customer_order_no);
  }
};
const getOrder = async (val) => {
  try {
    const { data, code, message } = await getOrderDetail({
      query: [{ field: "order_sn", queryType: "terms", value: [val] }],
      pageNum: 1,
      pageSize: 10,
    });
    if (code !== 200) return;
    let formValues = form.value.getFormValues();
    model.value = Object.assign({}, formValues, {
      destination_country: data.orders[0]?.recipient?.recipient_country || null,
      zip_code: data.orders[0]?.recipient?.recipient_zip_code || null,
      warehouse: data.orders[0]?.logistics?.ship_warehouse_id || null,
      city: data.orders[0]?.recipient?.recipient_city || null,
      delivery_mode: [1, 3],
    });
  } catch (error) {}
};
const getOrderShipment = async (val) => {
  try {
    const { data, code, message } = await getOrderShipmentInfo({
      order_no: val,
    });
    if (code !== 200) return;
    let formValues = form.value.getFormValues();
    const { order_details = [], order_info = {} } = data || {};
    const totalQuantity = order_details?.reduce(
      (sum, item) => sum + item.quantity,
      0
    );
    const maxDimensions = order_details?.reduce(
      (max, item) => ({
        length:
          parseFloat(item.length) > parseFloat(max.length)
            ? parseFloat(item.length)
            : max.length,
        width:
          parseFloat(item.width) > parseFloat(max.width)
            ? parseFloat(item.width)
            : max.width,
        height:
          parseFloat(item.height) > parseFloat(max.height)
            ? parseFloat(item.height)
            : max.height,
      }),
      { length: 0, width: 0, height: 0 }
    );
    const { length, width, height } = maxDimensions;
    model.value = Object.assign({}, formValues, {
      sku_quantity: totalQuantity,
      package_weight: order_info?.total_charge_weight || null,
      volume: [length, width, height],
      delivery_mode: [2],
      destination_country: order_info?.country || null,
    });
  } catch (error) {}
};
const handleCalcMode = (val) => {
  model.value = { delivery_mode: [1, 3], freight_calc_mode: val };
};
const publicStyle = { style: { width: "235px" } };
const fieldList = ref([
  {
    field: "freight_calc_mode",
    label: "运费计算模式",
    type: "select",
    originField: "freight_calc_mode",
    full: true,
    itemStyle: { width: "95%", marginRight: 0 },
    itemProps: { onChange: handleCalcMode },
  },
  {
    field: "customer",
    label: "订单号",
    ...publicStyle,
    slot: "Number",
    show: ({ model }) => model.freight_calc_mode == 1,
  },
  {
    field: "platform_id",
    label: "平台",
    type: "select",
    ...publicStyle,
    slot: "platform",
  },
  {
    field: "sku_info",
    label: "SKU",
    slot: "SkuQuantity",
    full: true,
    show: ({ model }) => model.freight_calc_mode == 2,
  },
  // {
  //   field: "sku",
  //   type: "textarea",
  //   label: "sku",
  //   full: true,
  //   autosize: { minRows: 4, maxRows: 8 },
  //   itemStyle: { width: "100%", marginRight: 0 },
  //   itemProps: { onChange: handleSku, onInput: blurSku },
  // },
  // {
  //   field: "sku_quantity",
  //   label: "SKU数量",
  //   type: "inputNumber",
  //   style: { width: "100px" },
  //   itemProps: { min: 0 },
  // },
  {
    field: "package_weight",
    label: "包裹重量",
    append: "KG",
    style: { width: "200px" },
    itemProps: { min: 0 },
    show: ({ model }) => model.freight_calc_mode != 1,
  },
  {
    field: "volume",
    label: "长宽高",
    slot: "volume",
    show: ({ model }) => model.freight_calc_mode != 1,
  },
  {
    field: "destination_country",
    label: "目的国家",
    type: "select",
    originField: "country",
  },
  {
    field: "transport_type",
    label: "运输方式",
    multiple: true,
    type: "select",
    originField: "transport_type",
  },
  {
    field: "warehouse",
    label: "发货仓库",
    slot: "warehouse",
    ...publicStyle,
  },
  {
    field: "todo",
    label: "目的仓库",
    slot: "destination_country",
    ...publicStyle,
  },
  {
    field: "goods_attrs",
    label: "产品属性",
    type: "select",
    ...publicStyle,
    originField: "logisticsAttributes",
  },
  {
    field: "delivery_mode",
    label: "渠道优选类型",
    multiple: true,
    filterable: false,
    type: "select",
    ...publicStyle,
    originField: "channel_delivery_mode",
  },
  {
    field: "channel_id",
    label: "渠道名称",
    type: "select",
    origin: "map.channel",
    ...publicStyle,
    options: {
      labelKey: "channel_name",
      valueKey: "channel_id",
    },
  },
  {
    field: "zip_code",
    label: "邮编",
    ...publicStyle,
  },
  {
    field: "city",
    label: "城市",
    ...publicStyle,
  },
  {
    field: "is_run_api",
    label: "是否使用物流商API计算运费",
    type: "switch",
  },
  {
    field: "ex_unstock_warehouse",
    label: "排除无库存仓库",
    type: "switch",
  },
]);

onMounted(() => {
  getOptions();
});

const getOptions = async () => {
  try {
    const { data: logisticsAttributes } = await getLogisticsAttr();
    if (logisticsAttributes) {
      optionsData.value.logisticsAttributes = logisticsAttributes;
    }
  } catch (e) {
    console.error(e);
  }
};
const getCountrylist = async () => {
  const { data } = await getCountry();
  optionsData.value.country = data || [];
};
getCountrylist();

const handleSubmit = async () => {
  try {
    loading.value = true;
    const { volume, is_run_api, customer, ...formInfo } =
      await form.value.submit();
    const [length, width, height] = volume || [];
    let package_weight =
      formInfo.package_weight && parseFloat(formInfo.package_weight) * 1000;
    if (Array.isArray(formInfo?.sku_info)) {
      formInfo.sku_info = formInfo?.sku_info?.filter(
        (item) => item && item.sku
      );
    }
    const {
      code,
      data = [],
      message,
    } = await freightCalc({
      ...formInfo,
      ...customer,
      length,
      width,
      height,
      package_weight,
      is_run_api: is_run_api ? 1 : 0,
    });
    if (code !== 200) {
      emit("tableData", []);
      ElMessage.warning(message);
      return;
    }
    emit("tableData", data);
    ElMessage.success("计算成功");
  } catch (e) {
    emit("tableData", []);
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
  } finally {
    loading.value = false;
  }
};

const handleSelling = () => {
  emit("selling");
};

const handleReset = async () => {
  model.value = {};
  await nextTick();
  form.value.resetForm();
  emit("tableData", []);
};
</script>

<style lang="scss" scoped>
.freight-form {
  :deep(.el-form-item) {
    margin-right: 16px;
  }
}
</style>
